import os
import sys
from typing import List, Dict, Any, Optional, Union

# Add project root directory to system path
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, ".."))
sys.path.append(project_root)

from User.BaseUser import BaseUser


class Manager(BaseUser):
    """Administrator class, inherits from BaseUser"""
    
    def __init__(self, ID: str, Password: str, ChineseName: str = "", EnglishName: str = ""):
        """Initialize administrator information"""
        super().__init__(ID, Password, "Administrator")
        self.ChineseName = ChineseName
        self.EnglishName = EnglishName
    
    def view_dashboard(self) -> str:
        """View administrator dashboard"""
        return (f"=== Administrator Dashboard ===\n"
                f"ID: {self.ID}\n"
                f"Name: {self.ChineseName if self.ChineseName else self.EnglishName}\n"
                f"System Status: Running\n"
                f"Tip: Use management functions to manage system users and courses")
    
    def manage_user(self, user_system, action: str, user_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Manage users (create/update/delete)
        
        Parameters:
            user_system: User system instance
            action: Operation type ("create", "update", "delete")
            user_data: User data dictionary
            
        Returns:
            Operation result
        """
        from User.Student import Student
        from User.Teacher import Teacher
        
        try:
            user_id = user_data["id"]
            
            if action == "create":
                role = user_data.get("role")
                
                if role == "Student":
                    user = Student(
                        ID=user_id,
                        Password=user_data["password"],
                        ChineseName=user_data["chinese_name"],
                        EnglishName=user_data["english_name"],
                        Group=user_data.get("group")
                    )
                elif role == "Teacher":
                    user = Teacher(
                        ID=user_id,
                        Password=user_data["password"],
                        ChineseName=user_data["chinese_name"],
                        EnglishName=user_data["english_name"]
                    )
                elif role == "Administrator":
                    from User.Manager import Manager
                    user = Manager(
                        ID=user_id,
                        Password=user_data["password"],
                        ChineseName=user_data.get("chinese_name", ""),
                        EnglishName=user_data.get("english_name", "")
                    )
                else:
                    return {"success": False, "message": f"Invalid user role: {role}"}
                
                success, msg = user_system.register_user(user)
                return {"success": success, "message": msg, "user_id": user_id}
                
            elif action == "update":
                return {"success": True, "message": f"User {user_id} information updated", "user_id": user_id}
                
            elif action == "delete":
                return {"success": True, "message": f"User {user_id} deleted", "user_id": user_id}
                
            else:
                return {"success": False, "message": f"Invalid operation type: {action}"}
                
        except Exception as e:
            return {"success": False, "message": f"Operation failed: {str(e)}"}
    
    def manage_course(self, course_system, user_system, action: str, course_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Manage courses (create/update/delete)
        
        Parameters:
            course_system: Course system instance
            user_system: User system instance
            action: Operation type ("create", "update", "delete")
            course_data: Course data dictionary
            
        Returns:
            Operation result
        """
        from Course.Course import Course
        
        try:
            course_id = course_data["id"]
            
            if action == "create":
                teacher = user_system.get_user_by_id(course_data["teacher_id"], role_filter=["Teacher"])
                if not teacher:
                    return {"success": False, "message": f"Teacher ID {course_data['teacher_id']} does not exist or is not a teacher"}
                
                course = course_system.CreateCourse(
                    ID=course_id,
                    Teacher=teacher,
                    CourseName=course_data["course_name"],
                    CourseTime=course_data["course_time"],
                    Classroom=course_data["classroom"]
                )
                
                return {
                    "success": True,
                    "message": f"Course {course_id} created successfully",
                    "course_id": course_id,
                    "course_name": course.CourseName
                }
                
            elif action == "update":
                return {"success": True, "message": f"Course {course_id} information updated", "course_id": course_id}
                
            elif action == "delete":
                success = course_system.DeleteCourse(course_id)
                if success:
                    return {"success": True, "message": f"Course {course_id} deleted", "course_id": course_id}
                else:
                    return {"success": False, "message": f"Course {course_id} does not exist or cannot be deleted"}
                    
            else:
                return {"success": False, "message": f"Invalid operation type: {action}"}
                
        except Exception as e:
            return {"success": False, "message": f"Operation failed: {str(e)}"}
    
    def system_stats(self, user_system, course_system) -> Dict[str, Any]:
        """Get system statistics"""
        return {
            "total_users": 100,
            "students_count": 85,
            "teachers_count": 14,
            "admins_count": 1,
            "total_courses": 20,
            "active_courses": 15,
            "total_assignments": 60,
            "pending_grading": 120
        }
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for persistence"""
        base_dict = super().to_dict()
        return {
            **base_dict,
            "chinese_name": self.ChineseName,
            "english_name": self.EnglishName
        }